<template>
  <el-container class="team-application-container">
    <!-- 侧边栏 -->
    <el-aside class="sidebar">
      <el-menu
        :default-active="activeSection"
        @select="activeSection = $event"
        class="menu"
      >
        <el-menu-item index="applications">
          查看申请
          <!-- 当有未读申请时显示红点 -->
          <span v-if="applicantCount > 0" class="notification-badge">{{ applicantCount }}</span>
        </el-menu-item>
        <el-menu-item index="members">查看成员</el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 右侧内容区 -->
    <el-main class="content">
      <div class="board">
        <!-- 查看申请页面 -->
        <div v-if="activeSection === 'applications'" class="section">
          <h2>申请详情</h2>
          <div v-if="applications.length === 0">
            <p>暂无申请</p>
          </div>
          <div v-else>
            <el-card
              v-for="app in applications"
              :key="app.application_id"
              class="application-card"
            >
              <h3>申请人：{{ app.applicant.username }}</h3>
              <p><strong>申请内容：</strong>{{ app.application_text }}</p>
              <p><strong>申请时间：</strong>{{ app.created_at }}</p>
              <p>
                <strong>能力值：</strong>{{ app.applicant.ability }},
                <strong>参与积极性：</strong>{{ app.applicant.enthusiasm }},
                <strong>表达能力：</strong>{{ app.applicant.communication }},
                <strong>人气值：</strong>{{ app.applicant.popularity }},
                <strong>信用值：</strong>{{ app.applicant.credit }},
                <strong>已完成任务次数：</strong>{{ app.applicant.times }}
              </p>
              <el-button type="primary" @click="acceptApplication(app.application_id)">
                同意申请
              </el-button>
            </el-card>
          </div>
          <el-button type="default" @click="refreshApplications">刷新申请</el-button>
        </div>

        <!-- 查看成员页面 -->
        <div v-if="activeSection === 'members'" class="section">
          <h2>小组成员</h2>
          <div v-if="members.length === 0">
            <p>暂无更多成员</p>
          </div>
          <div v-else>
            <el-card
              v-for="member in members"
              :key="member.user_id"
              class="member-card"
            >
              <p><strong>成员ID：</strong>{{ member.user_id }}</p>
              <p><strong>成员姓名：</strong>{{ member.username }}</p>
            </el-card>
          </div>
          <el-button type="default" @click="fetchGroupMembers">刷新成员</el-button>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import { defineComponent, ref, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import {
  ElContainer,
  ElAside,
  ElMain,
  ElMenu,
  ElMenuItem,
  ElCard,
  ElButton,
} from "element-plus";
import axios from "@/axiosInstance";

export default defineComponent({
  name: "TeamApplication",
  components: {
    ElContainer,
    ElAside,
    ElMain,
    ElMenu,
    ElMenuItem,
    ElCard,
    ElButton,
  },
  setup() {
    const router = useRouter();

    // 路由参数
    const taskId = ref(null);
    const groupId = ref(null);
    const leaderId = ref(null); // 组长ID，从 query 中获取，前端参数名为 UserId
    const leaderName = ref(null); // 组长姓名

    // 当前激活的侧边栏选项
    const activeSection = ref("applications");

    // 申请相关数据
    const applications = ref([]);
    const applicantCount = ref(0);

    // 当前小组成员名单（排除组长）
    const members = ref([]);

    // 获取组长收到的申请详情
    const fetchApplications = async () => {
      try {
        const response = await axios.get("http://39.105.217.183:8000/api/application-details/", {
          params: {
            task_id: taskId.value,
            leader_id: leaderId.value,
          },
        });
        applications.value = response.data;
        // 计算未读申请数量
        applicantCount.value = applications.value.filter(app => !app.is_read).length;
      } catch (error) {
        console.error("获取申请详情失败：", error);
      }
    };

    // 同意申请
    const acceptApplication = async (applicationId) => {
      try {
        console.log("同意申请：", applicationId);
        const response = await axios.post("http://39.105.217.183:8000/api/accept-application/", {
          application_id: applicationId,
        });
        alert("申请已同意，申请人已加入小组！");
        // 刷新申请列表
        fetchApplications();
        // 刷新成员列表
        fetchGroupMembers();
      } catch (error) {
        console.error("同意申请失败：", error);
        alert("同意申请失败！");
      }
    };

    // 获取小组成员名单（包含组员，不包含组长）
    const fetchGroupMembers = async () => {
      try {
        const response = await axios.get("http://39.105.217.183:8000/api/score/group_members/", {
          params: {
            task_id: taskId.value,
            group_id: groupId.value,
          },
        });
        console .log("小组成员：", response.data);
        // 假设后端返回所有成员（包括组长），这里过滤掉组长
        members.value = response.data
      } catch (error) {
        console.error("获取小组成员失败：", error);
      }
    };

    // 刷新申请列表
    const refreshApplications = () => {
      fetchApplications();
    };

    onMounted(() => {
      const params = new URLSearchParams(window.location.search);
      taskId.value = params.get("taskId");
      groupId.value = params.get("groupId");
      leaderId.value = params.get("UserId"); // 注意前端传递的参数名
      leaderName.value = params.get("UserName");
      console.log("参数：", taskId.value, groupId.value, leaderId.value, leaderName.value);
      fetchApplications();
      fetchGroupMembers();
    });

    return {
      activeSection,
      applications,
      applicantCount,
      members,
      taskId,
      groupId,
      leaderId,
      leaderName,
      fetchApplications,
      fetchGroupMembers,
      refreshApplications,
      acceptApplication,
    };
  },
});
</script>

<style scoped>
.team-application-container {
  min-height: 100vh;
  display: flex;
}

.sidebar {
  width: 220px;
  background-color: #f5f5f5;
  padding-top: 20px;
  border-right: 1px solid #ebeef5;
}

.menu {
  border-right: none;
}

.content {
  padding: 20px;
  flex: 1;
  display: flex;
  justify-content: center;
}

.board {
  width: 800px; /* 固定宽度 */
  background-color: #ffffff;
  padding: 20px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section {
  margin-bottom: 20px;
}

.application-card {
  margin-bottom: 20px;
  padding: 15px;
}

.member-card {
  margin-bottom: 10px;
  padding: 10px;
}
.notification-badge {
  background-color: #ff4444;
  color: #fff;
  border-radius: 50%;
  padding: 2px 6px;
  font-size: 12px;
  margin-left: 8px;
}
</style>